package com.formiaomiao.demain.fragment;

import android.app.NotificationManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.formiaomiao.demain.R;
import com.formiaomiao.demain.activity.ChatActivity;
import com.formiaomiao.demain.activity.FriendActivity;
import com.formiaomiao.demain.activity.LoginActivity;
import com.formiaomiao.demain.activity.MainActivity;
import com.formiaomiao.demain.adapter.ContactAdapter;
import com.formiaomiao.demain.adapter.MsgListAdapter;
import com.formiaomiao.demain.base.BaseApplication;
import com.formiaomiao.demain.base.BaseFragment;
import com.formiaomiao.demain.base.BaseUrl;
import com.formiaomiao.demain.db.MsgBean;
import com.formiaomiao.demain.greendao.MsgBeanDao;
import com.formiaomiao.demain.model.EventbusChatBean;
import com.formiaomiao.demain.model.FriendDetailBean;
import com.formiaomiao.demain.model.MessageInfo;
import com.formiaomiao.demain.model.MsgListBean;
import com.formiaomiao.demain.model.UserBean;
import com.formiaomiao.demain.service.PushIntentService;
import com.formiaomiao.demain.util.Constants;
import com.formiaomiao.demain.util.DateUtils;
import com.formiaomiao.demain.util.MessageEvent;
import com.formiaomiao.demain.util.PreferenceUtils;
import com.formiaomiao.demain.util.PreferenceValues;
import com.formiaomiao.demain.util.PushUtils;
import com.formiaomiao.demain.util.SetLeftBgUtils;
import com.formiaomiao.demain.util.StaticValues;
import com.formiaomiao.demain.util.UseGlideUtils;
import com.formiaomiao.demain.weight.LoadingDialog;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.StoreHouseHeader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static android.content.Context.NOTIFICATION_SERVICE;

public class ImFragment extends BaseFragment implements MsgListAdapter.onItemClickListener {

    @BindView(R.id.rl_im)
    RecyclerView rlIm;
    Unbinder unbinder;


    public static boolean isshow = false;
    int msgcount = 0;

    LoadingDialog dialog;

    int selectindex = -1;

    List<String> usernames = new ArrayList<>();
    FriendDetailBean friendDetailBean = new FriendDetailBean();
    List<FriendDetailBean.DataBean> friendDetailBeanList = new ArrayList<>();

    MsgListBean listBean;
    List<MsgListBean> listBeanList = new ArrayList<>();
    List<EMConversation> emConversationList = new ArrayList<>();
    MsgListAdapter adapter;

    StringBuffer sb;

    MsgBeanDao msgBeanDao;

    public static ImFragment newInstance() {
        Bundle args = new Bundle();
        ImFragment fragment = new ImFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_im_layout, container, false);
        unbinder = ButterKnife.bind(this, v);
        EventBus.getDefault().register(this);
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
        ViewInit();
        return v;
    }

    private void ViewInit() {
        dialog = new LoadingDialog(getActivity());
        msgBeanDao = BaseApplication.getInstances().getDaoSession().getMsgBeanDao();
        rlIm.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new MsgListAdapter(getActivity(), listBeanList);
        rlIm.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
        GetMsgList();
    }

    private void GetMsgList() {
        sb = new StringBuffer();
        usernames.clear();
        emConversationList.clear();
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        for (Map.Entry<String, EMConversation> entry : conversations.entrySet()) {
            usernames.add(entry.getKey());
            emConversationList.add(entry.getValue());
        }
        sb.append("{\"userid\":"+StaticValues.userid+",\"data\":[");
        for (int i = 0; i < usernames.size(); i++) {
            sb.append("{\"username\":\"" + usernames.get(i) + "\"},");
        }
        sb.delete(sb.length() - 1, sb.length());
        sb.append("]}");
        FriendDataInit(sb.toString());
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            //相当于OnResume(),可以做相关逻辑
            isshow = true;
        } else {
            //相当于OnPause()
            isshow = false;
        }
    }

    /**
     * 获取用户详情
     *
     * @param json
     */
    private void FriendDataInit(String json) {
        OkGo.<String>post(BaseUrl.USERFRIENDDETAIL).params("usernamejson", json)
                .headers("Authorization", PreferenceUtils.getString(getActivity(), PreferenceValues.TOKEN))
                .tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.body().contains("200")) {
                    friendDetailBeanList.clear();
                    friendDetailBean = gson.fromJson(response.body(), FriendDetailBean.class);
                    friendDetailBeanList.addAll(friendDetailBean.getData());
                    listBeanList.clear();
                    for (int i = 0; i < friendDetailBean.getData().size(); i++) {
                        listBean = new MsgListBean();
                        listBean.setUserHead(friendDetailBean.getData().get(i).getUserHead());
                        listBean.setUserName(friendDetailBean.getData().get(i).getUserName());
                        listBean.setNickName(friendDetailBean.getData().get(i).getNickName());
                        listBean.setMsgCount(emConversationList.get(i).getUnreadMsgCount());
                        listBean.setFriendremarks(friendDetailBean.getData().get(i).getFriendremarks());
                        if (emConversationList.get(i).getLastMessage().getBody().toString().startsWith("image")) {
                            listBean.setMsgContent("[图片]");
                        } else if (emConversationList.get(i).getLastMessage().getBody().toString().startsWith("video")) {
                            listBean.setMsgContent("[视频]");
                        } else if (emConversationList.get(i).getLastMessage().getBody().toString().startsWith("voice")) {
                            listBean.setMsgContent("[语音]");
                        } else {
                            listBean.setMsgContent(emConversationList.get(i).getLastMessage().getBody().toString().substring(5,
                                    emConversationList.get(i).getLastMessage().getBody().toString().length() - 1));
                        }
                        listBean.setMsgTime(DateUtils.timess(emConversationList.get(i).getAllMessages().get(emConversationList.get(i).getAllMessages().size() - 1)
                                .getMsgTime()));
                        listBeanList.add(listBean);
                        msgcount += emConversationList.get(i).getUnreadMsgCount();
                    }
                    adapter.notifyDataSetChanged();
                    EventBus.getDefault().post(new MessageEvent("未读:" + msgcount));
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }

    private void PushDataInit(String username, final EMMessage messages) {
        OkGo.<String>post(BaseUrl.USERNAMESELECT)
                .headers("Authorization", PreferenceUtils.getString(getActivity(), PreferenceValues.TOKEN))
                .params("username", username).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.body().contains("200")) {
                    final UserBean userBean = gson.fromJson(response.body(), UserBean.class);
                    String data = "";
                    if (messages.getBody().toString().startsWith("txt")) {
                        data = messages.getBody().toString().substring(5,
                                messages.getBody().toString().length() - 1);
                    } else if (messages.getBody().toString().startsWith("image")) {
                        data = "[图片]";
                    } else if (messages.getBody().toString().startsWith("video")) {
                        data = "[视频]";
                    } else if (messages.getBody().toString().startsWith("voice")) {
                        data = "[语音]";
                    }
                    final String finalData = data;
                    new Thread(new Runnable() {
                        @RequiresApi(api = Build.VERSION_CODES.O)
                        @Override
                        public void run() {
                            PushUtils.showNotification(getActivity(), "private",
                                    userBean.getData().getId() + "", userBean.getData().getUserHead(),
                                    userBean.getData().getNickName(), finalData, userBean.getData().getNickName(),
                                    userBean.getData().getUserHead(), userBean.getData().getUserName(), "1");
                        }
                    }).start();
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(List<EventbusChatBean> msglist) {
        GetMsgList();
        for (int j = 0; j < msglist.size(); j++) {
            for (int i = 0; i < listBeanList.size(); i++) {
                if (listBeanList.get(i).getUserName().equals(msglist.get(j).getFrom())) {
                    emConversationList.get(i).markMessageAsRead(msglist.get(j).getMsgid());          //把一条消息置为已读
                    emConversationList.get(i).markAllMessagesAsRead();  //未读消息清零
                    listBeanList.get(i).setMsgCount(0);
                }
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvents(MessageEvent msg) {
        if (msg.getMessage().equals("好友关系变更")) {
            GetMsgList();
        } else if (msg.getMessage().contains("删除聊天记录")) {
            for (int i = 0; i < listBeanList.size(); i++) {
                if ((StaticValues.username + "#" + listBeanList.get(i).getUserName()).
                        equals(StaticValues.username + "#" + listBeanList.get(i).getUserName())) {
                    listBeanList.get(i).setMsgContent("");
                    adapter.notifyDataSetChanged();
                }
            }
        } else if (msg.getMessage().equals("清空未读消息")) {
            msgcount = 0;
            //所有未读消息数清零
            EMClient.getInstance().chatManager().markAllConversationsAsRead();
            for (int i = 0; i < listBeanList.size(); i++) {
                listBeanList.get(i).setMsgCount(0);
            }
            adapter.notifyDataSetChanged();
        } else if(msg.getMessage().startsWith("备注:")){
            GetMsgList();
        }
    }

    EMMessageListener msgListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            //收到消息
            GetMsgList();
            PushDataInit(messages.get(0).getFrom(), messages.get(0));
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //收到透传消息
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
            //收到已读回执
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
            //收到已送达回执
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            //消息状态变动
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void itemclickListener(View v, int i) {
        if (StaticValues.NotifyId != -2 && StaticValues.ispush) {
            NotificationManager manager = (NotificationManager) getActivity().getSystemService(NOTIFICATION_SERVICE);
            manager.cancel(StaticValues.NotifyId);
            StaticValues.NotifyId = -2;
        }
        selectindex = i;
        Intent intent = new Intent();
        intent.putExtra("id", friendDetailBeanList.get(i).getId());
        intent.putExtra("neteaseUid", friendDetailBeanList.get(i).getNeteaseUid());
        intent.putExtra("nickname", friendDetailBeanList.get(i).getNickName());
        intent.putExtra("userhead", friendDetailBeanList.get(i).getUserHead());
        intent.putExtra("username", friendDetailBeanList.get(i).getUserName());
        intent.putExtra("friendremarks", friendDetailBeanList.get(i).getFriendremarks()==null ?
                "" : friendDetailBeanList.get(i).getFriendremarks());
        intent.putExtra("UnreadMsgCount", emConversationList.get(i).getUnreadMsgCount());
        intent.putExtra("msg", emConversationList.get(i).getLastMessage().getBody().toString());
        if (emConversationList.get(i).getUnreadMsgCount() > 0) {
            msgcount -= emConversationList.get(i).getUnreadMsgCount();
            EventBus.getDefault().post(new MessageEvent("未读:" + msgcount));
            intent.putExtra("MsgId", emConversationList.get(i).getLastMessage().getMsgId());
        }
        intent.setClass(getActivity(), ChatActivity.class);
        emConversationList.get(i).markAllMessagesAsRead();  //未读消息清零
        emConversationList.get(i).markMessageAsRead(emConversationList.get(i).getLastMessage().getMsgId());          //把一条消息置为已读
        listBeanList.get(i).setMsgCount(0);
        adapter.notifyDataSetChanged();
        startActivity(intent);
    }

    @Override
    public void badgeDragListener(View v, int i) {
        if (StaticValues.NotifyId != -2 && StaticValues.ispush) {
            NotificationManager manager = (NotificationManager) getActivity().getSystemService(NOTIFICATION_SERVICE);
            manager.cancel(StaticValues.NotifyId);
            StaticValues.NotifyId = -2;
        }
        msgcount -= emConversationList.get(i).getUnreadMsgCount();
        EventBus.getDefault().post(new MessageEvent("未读:" + msgcount));
        emConversationList.get(i).markAllMessagesAsRead();  //未读消息清零
        emConversationList.get(i).markMessageAsRead(emConversationList.get(i).getLastMessage().getMsgId());          //把一条消息置为已读
        listBeanList.get(i).setMsgCount(0);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void deleteItemClick(View v, int i) {
        dialog.show();
        if (StaticValues.NotifyId != -2 && StaticValues.ispush) {
            NotificationManager manager = (NotificationManager) getActivity().getSystemService(NOTIFICATION_SERVICE);
            manager.cancel(StaticValues.NotifyId);
            StaticValues.NotifyId = -2;
        }
        //删除和某个user会话，如果需要保留聊天记录，传false
        EMClient.getInstance().chatManager().deleteConversation(listBeanList.get(i).getUserName(), true);
        List<MsgBean> msgBeans = msgBeanDao.loadAll();
        for (int j = 0; j < msgBeans.size(); j++) {
            if (msgBeans.get(j).getChatMsgId().equals(StaticValues.username + "#" + friendDetailBeanList.get(i).getUserName())) {
                msgBeanDao.deleteByKey(msgBeans.get(j).getId());
            }
        }
        msgcount -= emConversationList.get(i).getUnreadMsgCount();
        EventBus.getDefault().post(new MessageEvent("未读:" + msgcount));
//        msgBeanDao.deleteAll();
        listBeanList.remove(i);
        adapter.notifyDataSetChanged();
        dialog.dismiss();
    }
}
